<?php // CirrusInsight.php

class CirrusInsight {
	
	public static function ServiceResponse($success, $responseData=null, $jsonp=true, $time=null) {
		$response->success = $success;
		$response->responseData = (isset($responseData) ? Util::prune($responseData) : false);
		if (isset($time)) $response->responseData->t = $time;
		$response->accountInfo = Util::prune(self::AccountInfo());
		$response->version = CURRENT_VERSION;
		
		$output = json_encode($response);
		if ($jsonp) {
			if (array_key_exists('callback', $_REQUEST)) {
				$callback = $_REQUEST["callback"];
				if ($callback == '?') $callback = '';
				$output = $callback . "(" . $output . ")";
			}
		}
		
		return $output;
	}
		
	public static function ServiceError($errorCode, $forwardUrl="", $message="") {
		$serviceError = new stdClass();
		$serviceError->errorCode = $errorCode;
		if ($forwardUrl != "") $serviceError->forwardUrl = $forwardUrl;
		if ($message != "") $serviceError->message = $message;
		return $serviceError;
	}
		
	public static function AccountInfo($user=null) {
		$user_id = '';
		if (!isset($user) && !isset($_SESSION["user_id"])) {
			return false;
		} else if (!isset($user) && isset($_SESSION["user_id"])) {
			$user = new InsightUser($_SESSION["user_id"]);
		}
		
		if (!isset($user->user_id) || Util::isNullOrEmpty($user->refresh_token)) return false;
		
		$accountInfo = new stdClass();
			$accountInfo->UserId 				= $user->user_id;
			$accountInfo->OrgId 				= $user->org_id;
			$accountInfo->Username 			= $user->username;
			$accountInfo->DisplayName 	= $user->display_name;
			$accountInfo->Email 				= $user->email;
			$accountInfo->Timezone 			= $user->timezone;
			$accountInfo->TrialExpDate 	= $user->trial_exp_date;
			$accountInfo->SfdcRootUrl 	= $user->getInstanceUrl();
			$accountInfo->Locale 				= $user->locale;
			$accountInfo->FEInstance		= FE_INSTANCE;

			$accountInfo->Status 				= $user->status;
			$accountInfo->isTrial 			= (strtolower($user->status) == 'trial');
			$accountInfo->isActive 			= (strtolower($user->status) == 'active');
			$accountInfo->isExpired 		= (strtolower($user->status) == 'expired');

		if (isset($user)) {
			$user->doGlobalDescribe(); // should be superfluous, but it's harmless
			
			// list of 'what' objects a task can be related to
			$accountInfo->WhatIds	= $_SESSION[DESCRIBE_KEY]["WHAT_IDS"];
	
			// check to see if they have 'create' perms for each of these objects
			$accountInfo->hasCases = $user->hasObj("case", true);
			$accountInfo->hasOpportunities = $user->hasObj("opportunity", true);
			$accountInfo->hasLeads = $user->hasObj("lead", true);
			$accountInfo->hasContacts = $user->hasObj("contact", true);
			$accountInfo->hasPersonAccounts = $user->hasPersonAccounts();
		} else {
			$accountInfo->WhatIds = array();
			$accountInfo->hasCases = false;
			$accountInfo->hasOpportunities = false;
			$accountInfo->hasLeads = false;
			$accountInfo->hasContacts = false;
			$accountInfo->hasPersonAccounts = false;
		}
		
		return $accountInfo;
	}
	
	public static function getCIPerson($detail, $fromcache=true) {
		$values = array_values($detail);
		$cache = CICache::get($values[0]);
		if ($fromcache && $cache !== FALSE) {
			// retrieve from cache
			$person = json_decode($cache);
			$person->cacheHit = true;
			return $person;
		} else {
			$person = Salesforce::getPerson($detail);
			if (!isset($person->Type) && isset($detail["email"])) $person->getMatchingAccounts($detail["email"]);
			$person = Util::prune($person);
			
			// add to cache if we found someone
			if (isset($person->Id)) {
				try {
					$cached = json_encode($person);
					if ($cached !== FALSE) CICache::add($values[0], $cached);
				} catch (Exception $e) { }
			}

			// Do Google Apps domain lookup
			if (isset($detail["email"])) {
				$person->doLookup = DomainLookup::GoogleAppsLookup($detail["email"]);
			}
			
			return $person;
		}
	}
        
        public static function Authorized() {
		if (!isset($_SESSION["access_token"]) || !isset($_SESSION["partner_endpoint"])) {
			if (isset($_COOKIE["insight_token"])) {
				$token = urldecode($_COOKIE["insight_token"]);
				$user_id = Util::decrypt($token);

				$user = new InsightUser($user_id);
				if (isset($user->user_id) && isset($user->refresh_token) && !!Util::decrypt($user->refresh_token)) {
					$user->requestAccessToken();
				}

				// return false if there's still no info
				if (!isset($_SESSION["access_token"]) || !isset($_SESSION["partner_endpoint"])) return false;
			} else {
				return false;
			}
		}
		return true;
	}
}
?>